package mapspinner;

import com.jme.math.Vector3f;

public class TerrainStreamer implements Runnable {
	/**
	 * This class runs as a separate process, calling the asynchronous methods
	 * of Terrain to continuously update the displayed terrain.
	 */
	private final Vector3f loadCenter;
	private final Terrain terrain;
	private final TerrainKey currentKey = new TerrainKey(0);
	private boolean preload;

	public TerrainStreamer(final boolean preload, final Terrain manager, final Vector3f loadCenter) {
		terrain = manager;
		this.preload = preload;
		this.loadCenter = loadCenter;
		if(preload)terrain.buildTerrainNodes();
	}

	/**
	 * this calls the shiftTerrain function if the camera moved one key space or
	 * more
	 * 
	 * @return true if any shifts have been performed
	 */
	public boolean action() {
		final TerrainKey camKey = new TerrainKey(terrain
				.worldToKey(loadCenter.x), terrain.worldToKey(loadCenter.z));
		if (camKey.distance(currentKey) > 1) {
			terrain.shiftTerrain(camKey.x - currentKey.x, camKey.z
					- currentKey.z);
			currentKey.x = camKey.x;
			currentKey.z = camKey.z;
			return true;
		}
		terrain.updateGrass();
		return false;
	}

	/**
	 * Start the streaming mechanism
	 */
	public void run() {
		if(!preload) terrain.buildTerrainNodes();
		while (true)
			if (!action())
				try {
					Thread.sleep(10);
				} catch (final InterruptedException e) {
				}
	}
}
